package org.example.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @version 1.0.0
 * @author: lynn
 * @description:  https://www.bilibili.com/video/BV1p441117dd?from=search&seid=16920829990041795326
 * @date: 2021/8/9 10:53
 */
public class LC56 {
    public static void main(String[] args) {
        LC56 lc=new LC56();
        int[][] intervals={{1,5},{2,3},{3,4}};
        int [][] res=lc.merge(intervals);
        for (int i = 0; i <res.length ; i++) {
            System.out.println(Arrays.toString(res[i]));
        }
        System.out.println("max job is: "+lc.maxJob(intervals));
    }





    //fixme 可以引申出自习室的问题

    /**
     * 1.难点，是在返回是数组，你肯定是不能马上确定的嘛，所以要用list接收，然后转成array
     * 2.然后就是list，怎么转成二维数组， list.toArray(int[list.size()][2]);
     */
    public int[][] merge(int[][] intervals) {
        if (intervals.length<=1|| intervals==null ){
            return intervals;
        }

        List<int[]> result=new ArrayList<>();
        //二维排序，就是按照index=0，或者index=1，这里是按照index=0进行排序
        Arrays.sort(intervals,(o1,o2)->{return o1[0]-o2[0];});
        result.add(intervals[0]);
        for (int i = 1; i <intervals.length ; i++) {
            //然后就可以看出list的优势，我可以把list排着末尾的取出来，然后跟单前数组的前缀比较
            int[] lastArray=result.get(result.size()-1);
            if (lastArray[1]>=intervals[i][0]){
                lastArray[1]=Math.max(lastArray[1],intervals[i][1]);
            }else {
                result.add(intervals[i]);
            }
        }
        return result.toArray(new int[result.size()][2]);
    }


    public int maxJob(int[][] intervals){
        int count=0;
        if (intervals.length<=1|| intervals==null ){
            return intervals.length;
        }
        Arrays.sort(intervals,((o1, o2) -> {return o1[1]-o2[1];}));
        int start=0;
        int end=23;
        for (int i = 0; i <intervals.length ; i++) {
            int[] tmp=intervals[i];
            if (tmp[0]>=start &&tmp[1]<=end){
                    count++;
                    start=tmp[1];
            }
        }
        return count;
    }
}
